package com.changpei.log.controller;

import com.alibaba.fastjson.JSON;
import com.alibaba.fastjson.JSONObject;
import com.changpei.common.cache.UserCache;
import com.changpei.common.result.Result;
import com.changpei.log.service.LogService;
import lombok.extern.slf4j.Slf4j;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.web.bind.annotation.*;

import java.util.Map;

/**
 * @author Way on 2021/8/15
 */
@RestController
@RequestMapping("/log")
@CrossOrigin
@Slf4j
public class LogController {

    @Autowired
    private UserCache userCache;

    @Autowired
    private LogService logService;

    @PostMapping(value = "/start")
    public Result<Boolean> start(@RequestBody Map<String, Object> param) {
        // 记录启动日志
        try {
            JSONObject cm = JSONObject.parseObject(JSON.toJSONString(param.get("cm")));
            cm.put("uid", userCache.getUserId(param.get("token").toString()));
            log.info(cm.toJSONString());
        } catch (Exception e) {
            log.warn("记录启动日志异常：", e.getMessage());
            return Result.ok(true);
        }
        return Result.ok(true);
    }

    @PostMapping(value = "/events")
    public Result<Boolean> events(@RequestBody Map<String, Object> param) {
        // 记录启动日志
        logService.process(param);
        return Result.ok(true);
    }

    @PostMapping(value = "/history")
    public Result<Boolean> history(@RequestBody Map<String, Object> param) {
        try {
            Long contentId = Long.parseLong(param.get("contentId").toString());
            String token = param.get("token").toString();
            Long viewTime = Long.parseLong(param.get("viewTime").toString());
//            Integer categoryId = Integer.parseInt(param.get("categoryId").toString());
            JSONObject jsonObject = new JSONObject();
            jsonObject.put("contentId", contentId);
            jsonObject.put("viewTime", viewTime);
//            jsonObject.put("categoryId", categoryId);
            userCache.addViewHistory(userCache.getUserId(token), jsonObject);
        } catch (Exception e) {
            e.printStackTrace();
            log.warn("历史记录异常：", e.getMessage());
            return Result.ok(true);
        }
        return Result.ok(true);
    }
}
